package com.lottery.game.runner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.game.common.utils.DateUtils;
import com.lottery.game.core.modules.entity.user.ChatRecord;
import com.lottery.game.core.modules.service.app.ChatRecordService;
import com.lottery.game.core.modules.service.app.OperationalSetService;
import com.lottery.game.websocket.MyHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;

/**
 * 用RobotExecutor替代该类
 * @author Administrator
 *
 */
@Deprecated
//@Component
public class RobotManager {
	Logger logger = LoggerFactory.getLogger(UpdateRobotData.class);

	@Autowired
	private OperationalSetService operationalSetService;

	@Autowired
	private ChatRecordService chatRecordService;

	public void runRobotManager() {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				Random random = new Random();
				while (true) {
					try {
						int pmin=1;
						int psize=3;
						int pmax=200;
						Map<String, Object> resultMap=operationalSetService.queryDictRobot();
						if(resultMap!=null) {
							pmin=Integer.parseInt((String)resultMap.get("min"));
							psize=Integer.parseInt((String)resultMap.get("size"));
							pmax=Integer.parseInt((String)resultMap.get("max"));
						}
						int r = random.nextInt(pmax - pmin +pmin) +pmin;// 获取线程休眠的时间
						logger.info(r + "秒后更新机器人信息!");
						Thread.sleep(r * 1000);
						logger.info("开始推送机器人信息！");
						int s = random.nextInt(psize - 1 + 1) + 1;// 获取随机的机器人个数
						// 获取房间的信息
						List<String> roomList = operationalSetService.queryRoomId();
						if (roomList != null && roomList.size() >= 1) {
							for (int i = 0; i < roomList.size(); i++) {
								String roomNumber = roomList.get(i);
								// 获取机器人信息
								List<Map<String, Object>> robotData = operationalSetService.queryRobotData(roomNumber);
								if (robotData == null || robotData.size() < 1) {
									continue;
								}

								/*
								 * int[] getrobot=new int[s];
								 *
								 * for (int k = 0; k < getrobot.length;) {
								 * getrobot[k]=random.nextInt(robotData.size()-0+0)+0;
								 * if(CheckRandom(getrobot,getrobot[k],k)){ k++; } }
								 */

								int getrobot = 0;// 记录上传循环的结果
								int m = 0;// 记录以及随机了多少个机器人
								if (robotData.size() <= psize && robotData.size() >= 1) {
									for (int j = 0; j < robotData.size(); j++) {
										Map<String, Object> itemMap = robotData.get(j);
										String roomNum = (String) itemMap.get("roomNumber");
										String robotName = (String) itemMap.get("robotName");
										String robotLv = (String) itemMap.get("userLv");
										String robotIcon=(String) itemMap.get("robotIcon");
										sendMsgToRoom(roomNum, robotName, robotLv,robotIcon);// 往房间里面推送机器人信息
										int sleepTime = (random.nextInt(5)+5)*1000;
										Thread.sleep(sleepTime);
									}
								} else {
									for (int j = 0; j < robotData.size(); j++) {
										int robots = random.nextInt(robotData.size() - 0 + 0) + 0;
										while (true) {
											if (robots == getrobot) {
												robots = random.nextInt(robotData.size() - 0 + 0) + 0;
											} else {
												getrobot = robots;
												break;
											}
										}
										Map<String, Object> itemMap = robotData.get(robots);
										String roomNum = (String) itemMap.get("roomNumber");
										String robotName = (String) itemMap.get("robotName");
										String robotLv = (String) itemMap.get("userLv");
										String robotIcon=(String) itemMap.get("robotIcon");
										sendMsgToRoom(roomNum, robotName, robotLv,robotIcon);// 往房间里面推送机器人信息
										int sleepTime = (random.nextInt(5)+5)*1000;
										Thread.sleep(sleepTime);
										m += 1;
										if (m == s) {
											break;
										}
									}
								}
							}
						}
					} catch (Exception e) {
						logger.info(String.format("机器人推送异常%s",e));
						e.printStackTrace();
					}
				}

			}
		});

		thread.start();
	}

	private void sendMsgToRoom(String roomNuber, String robotName, String robotLv,String robotIcon) {
		String now = DateUtils.getNowDateString();
		Map<String, Object> msgMap = new HashMap<>();
		Map<String, String> paraMap = new HashMap<>();
		Map<String, String> paramMap = new HashMap<>();
		paraMap.put("mySendTime", now);
		paraMap.put("robotName", robotName);
		paraMap.put("robotLv", robotLv);
		paraMap.put("nowTime", now);
		//数据库使用
		paramMap.put("roomNumber", roomNuber);
		paramMap.put("sendernickname", robotName);
		paramMap.put("fristSend", "true");
		paramMap.put("message", robotLv);
		paramMap.put("photourl", robotIcon);
		paramMap.put("mySendTime", now);
		msgMap.put("robotInfo", paraMap);
		ChatRecord chatRecord = new ChatRecord();

		String uuid = UUID.randomUUID().toString();
		chatRecord.setId(uuid);
		chatRecord.setSenderUserid("robotInfo");
		chatRecord.setRoomnumber(roomNuber);
		String msg = JSON.toJSONString(paramMap);
		chatRecord.setMsgContent(msg);
		chatRecord.setSendernickname(robotName);
		chatRecord.setTimestamp(now);
		chatRecord.setSenderphoto(robotIcon);
		chatRecord.setMessageStatus("0");
		chatRecord.setChatType("0");
		chatRecord.setOrginMsg(robotLv);


		TextMessage message = new TextMessage(JSONObject.toJSONString(msgMap));
		Map<String, WebSocketSession> sessionMap = MyHandler.webSocketMap.get(roomNuber);
		if (sessionMap != null) {
			Iterator<Entry<String, WebSocketSession>> it = sessionMap.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, WebSocketSession> tmpSession = it.next();

				MyHandler.sendMessageToUser(tmpSession.getValue(), message);// 给房间的所有的发送消息
			}
		}
		chatRecordService.addChatRecord(chatRecord);
	}

	public static boolean CheckRandom(int c[], int t, int l) {// 检查生成的随机数是否存在与数组中
		for (int i = 0; i < c.length; i++) {
			if (c[i] == t && l != i) {
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args) {
	}

}
